#coding:utf-8
from django.http import HttpResponse,HttpResponseRedirect
from  django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.template import RequestContext
from django.conf import settings
import httplib2
from urllib import urlencode
from django.core.paginator import Paginator
from base.models import *
from forms import *
import json,datetime,time,hashlib
def checklogin(func):
    def warp(request):
        if int(request.session.get('user_id',0))<1:
            return HttpResponseRedirect('/login')
        return func(request)
    return warp
def common(request):
    return {
        'VERSION': settings.VERSION,
        'LAST': settings.LAST,
    }
def index(request):
    return render_to_response('index.html',context_instance = RequestContext(request,processors=[common]))


@csrf_exempt
#将用户提交的店铺地址、用户邮箱等信息写入任务队列
def add_queue(request):
    form = TaskForm(request.POST)
    scrapy_error = False
    c = {'status':'ok','msg':u'任务添加成功'}
    if form.is_valid():
        data = form.cleaned_data['data']
        print data
        mail = data['address']
        task_list = data['urls']
        for item in task_list:
            Q = Queue(url=item,mail=mail)
            Q.save()
            if not run_scrapy():
                scrapy_error = True
                c = {'status':'error','msg':u'爬虫服务器连接失败'}
    else:
        return HttpResponse(json.dumps({'status':'error','msg':form['data'].errors}))

    return HttpResponse(json.dumps(c,ensure_ascii=False))

#运行scrapy
def run_scrapy():
     http = httplib2.Http()
     data={'project':"dirbot","spider":"taobao"}
     header={'Content-Type': 'application/x-www-form-urlencoded'}
     try:
        s,c = http.request("http://localhost:6800/schedule.json","POST",urlencode(data),headers=header)
     except Exception:
         return False
     return True

@csrf_exempt
def loginView(request):
    return render_to_response('center/login.html',context_instance = RequestContext(request))
#后台管理中心首页
@checklogin
def centerView(request):
   return render_to_response('center/index.html',context_instance = RequestContext(request))

def helpView(request):
   return render_to_response('center/help.html',context_instance = RequestContext(request))
def displayView(request):
        day =   datetime.date.today()
        day_s = day+datetime.timedelta(-20)
        day =day.strftime("%Y-%m-%d")
        day_s =day_s.strftime("%Y-%m-%d")
        id = int(request.GET.get('id',0))
        uid = request.session.get('user_id',1)
        try:
            Task.objects.get(id=id,user_id=uid)
        except Exception:
            return render_to_response('center/display.html',locals())
        s_date = request.GET.get('s_date','2013-05-1')
        e_date = request.GET.get('e_date','2013-10-10')
        m =Store_info.objects.filter(task_id=id,date__gte=s_date,date__lt=e_date)[0:15]
        cate = []
        sale_num= []
        sale_money =[]
        for i in m:
            cate.append(i.date.strftime("%m-%d"))
            sale_num.append(i.sale_count)
            sale_money.append(i.sale_money)
        return render_to_response('center/display.html',locals(),context_instance = RequestContext(request))
@checklogin
def tasklistView(request):
    uid = request.session.get('user_id',0)
    m = Task.objects.filter(user_id=uid)
    p = Paginator(m , 4)
    page_count = p.num_pages
    page = int(request.GET.get('page',1))
    if page >page_count:
        page = page_count
    elif page<1:
        page =1
    m=p.page(page)
    return render_to_response('center/list.html',{'item':m,'page_count':page_count,'page':page},context_instance = RequestContext(request))

def editView(request):
    id = int(request.GET.get('id',0))
    if id<1:
        return HttpResponseRedirect('list')
    task = Task.objects.get(id=id)
    store_name = task.store.store_name
    return render_to_response('center/edit.html',locals(),context_instance = RequestContext(request))
@csrf_exempt
def update(request):
    tid = int(request.POST.get('tid',0))
    sid = int(request.POST.get('sid',0))
    if tid<1 or sid<1:
        c = {'status':'error','msg':u'参数非法'}
    else:
        form = Task1Form(request.POST)
        if form.is_valid():
            store = Store.objects.get(id=sid)
            store.store_url = form.cleaned_data['store_url']
            store.save()

            task = Task.objects.get(id=tid)
            task.task_name =form.cleaned_data['task_name']
            task.stat = form.cleaned_data['stat']
            task.save()
            c = {'status':'ok','msg':u'修改成功'}
        else:
            return HttpResponse(json.dumps({'status':'error','msg':form.errors}))
    return HttpResponse(json.dumps(c,ensure_ascii=False))

@csrf_exempt
def doAdd(request):
    form = Task1Form(request.POST)
    if form.is_valid():
        store = Store()
        store.store_name = form.cleaned_data['store_name']
        store.store_url = form.cleaned_data['store_url']
        store.save()
        task = Task()
        task.task_name =form.cleaned_data['task_name']
        task.user_id =request.session.get('user_id',1)
        task.store_id =store.id
        task.stat = form.cleaned_data['stat']
        task.save()
        c = {'status':'ok','msg':u'添加成功'}
    else:
        return HttpResponse(json.dumps({'status':'error','msg':form.errors}))

    return HttpResponse(json.dumps(c,ensure_ascii=False))

@csrf_exempt
def del_task(request):
    id = int(request.POST.get('id',0))
    json_msg ={'status':'ok','msg':u'删除成功'}
    if id<1:
        json_msg['msg'] =u'不存在该条记录，删除失败'
        json_msg['status'] ='error'
    else:
        try:
            task = Task.objects.get(id=id)
            store = Store.objects.get(id=task.store_id).delete()
            task.delete()
        except Exception:
            json_msg['msg'] =u'删除失败'
            json_msg['status'] ='error'
    return HttpResponse(json.dumps(json_msg,ensure_ascii=False))

@csrf_exempt
def dologin(request):
    from_url = request.META.get('HTTP_REFERER','/')
    username = request.POST.get('username',0)
    password = request.POST.get('password',0)
    user = User.objects.filter(username=username)
    msg =u'账号信息不正确!'
    if user.count()>0 :
        user = user[0]
        if user.password==hashlib.md5(password).hexdigest():
            request.session['user_id'] =user.id
            request.session['user_name'] =user.username
            request.session.set_expiry(0)
            return HttpResponseRedirect('/list')
    return showMsg(request,from_url,msg)

def logout(request):
    try:
        del request.session['user_id']
        del request.session['user_name']
    except KeyError:
        pass
    return HttpResponseRedirect('/login')

def showMsg(request,url,msg):
    return render_to_response('msg.html',locals())
@csrf_exempt
def regHandle(request):
    from_url = request.META.get('HTTP_REFERER','/')
    username = request.POST.get('username',0)
    password = request.POST.get('password',0)
    msg = u'注册失败！请检查您的注册信息'
    if username and password:
        try:
            user = User.objects.get(username=username)
            msg =u'该用户已经存在！'
        except Exception:
            msg =u'注册成功！'
            user =User(username=username,password=hashlib.md5(password).hexdigest())
            user.save()
    return showMsg(request,from_url,msg)






